// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <pollux/functions/lib/aggregates/tests/utils/AggregationTestBase.h>
#include <pollux/functions/sparksql/aggregates/register.h>

using namespace kumo::pollux::functions::aggregate::test;

namespace kumo::pollux::functions::aggregate::sparksql::test {

namespace {
class RegrReplacementAggregationTest : public AggregationTestBase {
 protected:
  void SetUp() override {
    AggregationTestBase::SetUp();
    registerAggregateFunctions("spark_");
  }
};

TEST_F(RegrReplacementAggregationTest, groupBy) {
  vector_size_t size = 1'000;
  auto data = make_row_vector({
      make_flat_vector<int32_t>(size, [](auto row) { return row % 10; }),
      make_flat_vector<double>(size, [](auto row) { return row * 0.1; }),
  });

  createDuckDbTable({data});
  // m2 is equal to the population variance divided by the size of the group.
  testAggregations(
      {data},
      {"c0"},
      {"spark_regr_replacement(c1)"},
      {"c0", "a0 / 100.0"},
      "select c0, var_pop(c1) from tmp group by c0");
  testAggregationsWithCompanion(
      {data},
      [](auto& /*builder*/) {},
      {"c0"},
      {"spark_regr_replacement(c1)"},
      {{DOUBLE()}},
      {"c0", "a0 / 100.0"},
      "select c0, var_pop(c1) from tmp group by c0");
}

TEST_F(RegrReplacementAggregationTest, global) {
  vector_size_t size = 1'000;
  auto data = make_row_vector({
      make_flat_vector<double>(size, [](auto row) { return row * 0.3; }),
  });

  createDuckDbTable({data});
  // m2 is equal to the population variance divided by the size of the group.
  testAggregations(
      {data},
      {},
      {"spark_regr_replacement(c0)"},
      {"a0 / 1000.0"},
      "select var_pop(c0) from tmp");
  testAggregationsWithCompanion(
      {data},
      [](auto& /*builder*/) {},
      {},
      {"spark_regr_replacement(c0)"},
      {{DOUBLE()}},
      {"a0 / 1000.0"},
      "select var_pop(c0) from tmp");
}

} // namespace
} // namespace kumo::pollux::functions::aggregate::sparksql::test
